<template>
	<el-card class="box-card">
		<div slot="header" class="clearfix">
			<span>发布文章</span>
		</div>
		<el-form :model="form" ref="form" :rules="rules" label-width="100px">
			<el-form-item label="标题" prop="title">
				<el-input v-model="form.title"></el-input>
			</el-form-item>
			<el-form-item label="描述" prop="description">
				<el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="form.description"></el-input>
			</el-form-item>
			<el-form-item label="分类">
				<el-col :span="6">
					<el-select v-model="form.cate_1st" placeholder="请选择一级分类">
						<el-option v-for="item in cate_1st_options" :key="item.cate_id" :label="item.cate_name"
							:value="item.cate_id">
						</el-option>
					</el-select>
				</el-col>
				<el-col :span="6">
					<el-select v-model="form.cate_2nd" placeholder="请选择二级分类">
						<el-option v-for="item in cate_2nd_options" :key="item.cate_id" :label="item.cate_name"
							:value="item.cate_id">
						</el-option>
					</el-select>
				</el-col>
			</el-form-item>
			<el-form-item label="主图" prop="main_photo">
				<UploadPhoto v-model="form.main_photo"></UploadPhoto>
			</el-form-item>
			<el-form-item label="内容" prop="content">
				<div style="border: 1px solid #ccc;">
					<Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
						:mode="mode" />
					<Editor style="height: 500px; overflow-y: hidden;" v-model="form.content" :defaultConfig="editorConfig"
						:mode="mode" @onCreated="onCreated" />
				</div>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="handleRelease">发布文章</el-button>
			</el-form-item>
		</el-form>
	</el-card>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
import { Category } from '@/api';
import UploadPhoto from '@/components/UploadPhoto.vue';
import { Article } from "@/api";
// 处理WangEditor的初始化问题
import { Boot } from '@wangeditor/editor';
// editor为空获取value值存在"<p><br></p>"，在表单中无法校验，借助于插件解决
function withEmptyHtml(editor) {
	const { getHtml } = editor
	const newEditor = editor
	newEditor.getHtml = () => {
		if (newEditor.isEmpty()) {
			return ''
		}
		return getHtml()
	}
	return newEditor
}
// 注册插件
Boot.registerPlugin(withEmptyHtml);

export default {
	name: 'Release',
	// 布局注册
	components: { Editor, Toolbar, UploadPhoto },
	data() {
		return {
			form: {
				cate_1st: '',
				cate_2nd: '',
				title: '',
				description: '',
				main_photo: '',
				// 富文本编辑器的内容在content内
				content: '',
			},
			cate_1st_options: [],
			cate_2nd_options: [],
			editor: null,
			toolbarConfig: {},
			editorConfig: {
				placeholder: '请输入内容...',
				MENU_CONF: {
					uploadImage: {
						server: `${process.env.VUE_APP_SERVER}/upload/editor/`,
						// 自定义增加 http  header
						headers: {
							Authorization: `Bearer ${sessionStorage.access_token}`,
						},
						// form-data fieldName ，默认值 'wangeditor-uploaded-image'
						fieldName: 'file',
					}
				}
			},
			mode: 'default', // or 'simple' 简化版
			rules: {
				title: [{ required: true, message: "请填写文章标题！", trigger: 'blur' }],
				description: [{ required: true, message: "请填写文章描述！", trigger: 'blur' }],
				main_photo: [{ required: true, message: "请上传文章主图！", trigger: 'blur' },],
				content: [{ required: true, message: "请输入文章内容！", trigger: 'blur' },],
			},
		}
	},
	async created() {
		document.title = "发布文章页面";
		// 加载一级分类
		this.cate_1st_options = await this.loadSubcate(0);
		this.form.cate_1st = this.cate_1st_options[0].cate_id;
	},
	// watch侦听器、计算属性等使用箭头函数会导致this的指向问题
	watch: {
		"form.cate_1st": async function (newValue, oldValue) {
			// console.log(newValue, oldValue);
			// 监控form.cate_1st变化，加载二级分类
			this.cate_2nd_options = await this.loadSubcate(newValue);
			// 默认选中第一项;ES6新增?；如果继续执行?后面代码会报错，那么?后面的代码不执行
			this.form.cate_2nd = this.cate_2nd_options[0]?.cate_id;
		},
	},
	methods: {
		onCreated(editor) {
			this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
		},
		// 加载子级分类
		async loadSubcate(cate_id) {
			let { status, msg, data } = await Category.sub({ cate_id });
			if (status) {
				return data;
				// async函数return出去的是Promise对象
			}
		},
		// 发布文章
		handleRelease() {
			this.$refs.form.validate(async (valid) => {
				if (valid) {
					let { status, msg } = await Article.release({ ...this.form });
					if (status) {
						this.$message.success(msg);
						this.$router.push('/article/list');
					} else {
						this.$message.error(msg);
					}
				}
			});
		}
	},
	beforeDestroy() {
		const editor = this.editor
		if (editor == null) return
		editor.destroy() // 组件销毁时，及时销毁编辑器
	},
}
</script>

<style>
.el-input {
	margin-right: 30px;
}
</style>
